$(function() {

    $(".form-myt-sale-sale-return-bpmInput").data("formOptions", {
        updateTotalAmount : function() {
            var $form = $(this);

            var $grid = $form.find(".grid-myt-sale-sale-return-bpmInput");
            var userData = {
                "commodity.display" : "合计："
            };
            // 更新表格汇总统计数据
            userData.amount = $grid.jqGrid('sumColumn', 'amount');
            userData.commodityAmount = $grid.jqGrid('sumColumn', 'commodityAmount');
            userData.costAmount = $grid.jqGrid('sumColumn', 'costAmount');
            userData.lossAmount = $grid.jqGrid('sumColumn', 'lossAmount');
            userData.deliveryAmount = $grid.jqGrid('sumColumn', 'deliveryAmount');
             
            $grid.jqGrid("footerData", "set", userData, true);
            var totalReturnAmount=userData.amount+userData.deliveryAmount;
            $form.find(".span-total-return-amount").html(totalReturnAmount);
            $form.setFormDatas({
                totalCommodityAmount :  userData.commodityAmount,
                totalLossAmount : userData.lossAmount,
                totalCostAmount : userData.costAmount,
                totalSaleAmount : userData.amount ,
                totalReturnAmount:totalReturnAmount,
                deliveryAmount : userData.deliveryAmount
            });
        },
        bindEvents : function() {
            var $form = $(this);
            var $grid = $form.find(".grid-myt-sale-sale-return-bpmInput");

            Biz.setupCustomerProfileSelect($form);

            //扫描枪输入处理
            $form.find("input[name='barcodeScan']").barcodeScanSupport({
                onEnter : function() {
                    var code = $(this).val();
                    if (code != '') {
                        var data = Biz.queryCacheCommodityDatas(code);
                        if (data && data.length > 0) {
                            var rowdata = data[0];
                            var ids = $grid.jqGrid('getDataIDs');
                            var targetRowdata = null;
                            var targetRowid = null;
                            $.each(ids, function(i, id) {
                                var item = $grid.jqGrid('getRowData', id);
                                if (item['commodity.commodityBarcode'] == rowdata['commodityBarcode']) {
                                    if (item['gift'] != 'true') {
                                        targetRowid = id;
                                        targetRowdata = item;
                                        return false;
                                    }
                                }
                            });

                            if (targetRowdata) {
                                targetRowdata.quantity = Number(targetRowdata.quantity) + 1;
                                $grid.data("gridOptions").calcRowAmount.call($grid, targetRowdata);
                                $grid.jqGrid('setRowData', targetRowid, targetRowdata);
                            } else {

                                var newdata = {
                                    'commodity.id' : rowdata.id,
                                    'commodity.barcode' : rowdata.barcode,
                                    'measureUnit' : rowdata.measureUnit,
                                    'storageLocation.id' : rowdata['defaultStorageLocation.id'],
                                    'commodity.barcode' : rowdata.barcode,
                                    'commodity.title' : rowdata.title,
                                    'quantity' : 1,
                                    'discountAmount':0
                                }
                                newdata['price'] = rowdata['lastSalePrice'];
                                newdata['commodityPrice']=rowdata['lastPurchasePrice'];
                                $grid.data("gridOptions").calcRowAmount.call($grid, newdata);
                                $grid.jqGrid('insertNewRowdata', newdata);
                            }
                            $form.data("formOptions").updateTotalAmount.call($form);
                        }
                        $(this).focus();
                    }
                }
            });

            // 从销售单选取
            $form.find(".btn-select-sale-delivery").click(function() {
                var $saleDeliveryId = $form.find("input[name='saleDelivery.id']");
                var saleDeliveryId = $saleDeliveryId.val();
                if (saleDeliveryId != '') {
                    if (confirm("一个退换单只允许从单个销售单选取，重新选取将清空当前相关数据以新选择销售单数据覆盖，确认继续？")) {
                        $grid.clearGridData();
                        $form.data("formOptions").updateTotalAmount.call($form);
                        return;
                    }
                }

                $(this).popupDialog({
                    url : WEB_ROOT + '/myt/sale/sale-return!forward?_to_=selectSaleDelivery',
                    title : '选取销售单',
                    callback : function(data) {
                        var master = data.master;
                        var rows = data.rows;
                        $saleDeliveryId.val(master.id);
                        $form.setFormDatas({
                            'receivePerson' : master['receivePerson'],
                            'mobilePhone' : master['mobilePhone'],
                            'postCode' : master['postCode'],
                            'title' : master['title'],
                            'deliveryAddr' : master['deliveryAddr'],
                            'customerProfile.id' : master['customerProfile.id'],
                            'customerProfile.display' : master['customerProfile.display'],
                            'referenceVoucher' : master['voucher'],
                            'referenceSource' : 'MYT',
                            'memo' : master['memo']
                        }, true);
                        $.each(rows, function(i, row) {
                            row['commodityPrice'] = row['costPrice'];
                            row['commodityAmount'] = row['costAmount'];
                            row['storageLocation.id'] = row['storageLocation.id'];
                            row['storageLocation.display'] = row['storageLocation.display'];
                            row['batchNo'] = row['batchNo'];
                            row['expireDate'] = row['expireDate'];
                            row['lossAmount']=0;
                            $grid.data("gridOptions").calcRowAmount.call($grid, row);
                            var newid = $grid.jqGrid('insertNewRowdata', row);
                            var idx = $grid.find("tr[id='" + newid + "'] >td.jqgrid-rownum").html().trim();
                            $grid.jqGrid('setRowData', newid, {
                                subVoucher : 100 + idx * 10
                            });
                            $form.data("formOptions").updateTotalAmount.call($form);
                        });
                    }
                })
            });
            
            //按金额自动分摊运费
            $form.find(".btn-delivery-by-amount").click(function() {

                if ($grid.jqGrid("isEditingMode", true)) {
                    return false;
                }
                //按照“原价金额”的比率计算更新每个行项的折扣额，注意最后一条记录需要以减法计算以修正小数精度问题
                var totalDeliveryAmount = $form.find("input[name='deliveryAmount']").val();
                var totalOriginalAmount = $grid.jqGrid('sumColumn', 'originalAmount');

                var perDeliveryAmount = MathUtil.div(totalDeliveryAmount, totalOriginalAmount, 5);
                var lastrowid = null;
                var tempDeliveryAmount = 0;
                var ids = $grid.jqGrid("getDataIDs");
                $.each(ids, function(i, id) {
                    var rowdata = $grid.jqGrid("getRowData", id);
                    if (rowdata['commodity.id'] != '') {
                        rowdata['deliveryAmount'] = MathUtil.mul(perDeliveryAmount, rowdata['originalAmount']);
                        $grid.data("gridOptions").calcRowAmount.call($grid, rowdata, 'deliveryAmount');
                        $grid.jqGrid('setRowData', id, rowdata);
                        tempDeliveryAmount = MathUtil.add(tempDeliveryAmount, rowdata['deliveryAmount']);
                        lastrowid = id;
                    }
                });

                //最后一条记录需要以减法计算以修正小数精度问题
                if (lastrowid) {
                    var rowdata = $grid.jqGrid("getRowData", lastrowid);
                    rowdata['deliveryAmount'] = MathUtil.sub(totalDeliveryAmount, MathUtil.sub(tempDeliveryAmount, rowdata['deliveryAmount']));

                    $grid.data("gridOptions").calcRowAmount.call($grid, rowdata, 'deliveryAmount');
                    $grid.jqGrid('setRowData', lastrowid, rowdata);
                }

                $form.data("formOptions").updateTotalAmount.call($form);

            });
            
        },
       
    });

    $(".grid-myt-sale-sale-return-bpmInput").data("gridOptions", {
        calcRowAmount : function(rowdata, src) {
            rowdata['originalAmount'] = MathUtil.mul(rowdata['price'], rowdata['quantity']);
            rowdata['amount'] = MathUtil.sub(rowdata['originalAmount'], rowdata['discountAmount']);
            rowdata['commodityAmount'] = MathUtil.mul(rowdata['commodityPrice'], rowdata['quantity']);
            rowdata['costAmount'] =  MathUtil.add(MathUtil.add(rowdata['commodityAmount'], rowdata['lossAmount']),rowdata['deliveryAmount']);
            
        },
        updateRowAmount : function(src) {
            var $grid = $(this);
            var rowdata = $grid.jqGrid("getEditingRowdata");
            $grid.data("gridOptions").calcRowAmount.call($grid, rowdata, src);
            $grid.jqGrid("setEditingRowdata", rowdata);
        },
        batchEntitiesPrefix : "saleReturnDetails",
        url : function() {
            var pk = $(this).attr("data-pk");
            if (pk) {
                return WEB_ROOT + "/myt/sale/sale-return!saleReturnDetails?id=" + pk + "&clone=" + $(this).attr("data-clone");
            }
        },
        colModel : [ {
            label : '所属销售单主键',
            name : 'saleReturn.id',
            hidden : true,
            hidedlg : true,
            editable : true,
            formatter : function(cellValue, options, rowdata, action) {
                var pk = $(this).attr("data-pk");
                return pk ? pk : "";
            }
        },{
            name : 'commodityStock.id',
            hidden : true,
            hidedlg : true,
            editable : true
        }, {
            name : 'commodity.id',
            hidden : true,
            hidedlg : true,
            editable : true
        }, {
            name : 'saleDeliveryDetail.id',
            hidden : true,
            hidedlg : true,
            editable : true
        }, {
            name : 'commodity.barcode',
            hidden : true,
            hidedlg : true,
            editable : true
        }, {
            label : '行项号',
            name : 'subVoucher',
            width : 50,
            editable : true,
            editrules : {
                required : true
            },
            editoptions : {
                dataInit : function(elem) {
                    var $el = $(elem);
                    if ($el.val() == '') {
                        var $jqgrow = $el.closest(".jqgrow");
                        var idx = $jqgrow.parent().find(".jqgrow:visible").index($jqgrow);
                        $el.val(100 + idx * 10);
                    }
                }
            },
            align : 'center'
        }, {
            label : '商品编码',
            name : 'commodity.sku',
            width : 80,
            editable : true,
            editrules : {
                required : true
            },
            editoptions : {
                placeholder : '双击选取',
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.dblclick(function() {
                        var rowdata = $grid.jqGrid("getEditingRowdata");
                        $(this).popupDialog({
                            url : WEB_ROOT + '/myt/stock/commodity-stock!forward?_to_=selection',
                            postData : {
                                barcode : rowdata['commodity.barcode']
                            },
                            title : '选取库存商品',
                            callback : function(item) {
                                var ids = $grid.jqGrid('getDataIDs');// 返回当前grid里所有数据的id
                                
                                var existRowId = null;// 如果是已经选择过的商品，那么这是哪个商品的所在行行号
                                var oldQuantity = null;// 如果是已经选择过的商品，那么这是哪个商品的数量
                                for(i=0; i<ids.length; i++){
                                    var row = $grid.jqGrid('getRowData', ids[i]);//获取单行数据根据ID
                                    if(item['commodity.sku'] == row['commodity.sku'] && 
                                            item.batchNo == row.batchNo && 
                                            item['storageLocation.id'] == row['storageLocation.id']){
                                             // SKU，批次号，库存地一致，并且不是赠品即认为是同一商品
                                        existRowId = ids[i];
                                        oldQuantity = row.quantity;
                                        break;
                                    }
                                }
                                
                                if(existRowId){
                                    $grid.jqGrid("setRowData", existRowId, {
                                        'quantity' : MathUtil.add(oldQuantity,1)
                                    });
                                    var myrowdata = $grid.jqGrid('getRowData', existRowId);//获取单行数据根据ID
                                    $grid.data("gridOptions").calcRowAmount.call($grid, myrowdata);
                                    $grid.jqGrid("setRowData", existRowId, myrowdata);
                                }else{
                                    var myrowdata = {             
                                            'commodity.sku' : item['commodity.sku'],//商品唯一性标识
                                            'commodity.id' : item['commodity.id'],
                                            'commodity.barcode' : item['commodity.barcode'],
                                            'commodity.sku' : item['commodity.sku'],
                                            'commodity.display' : item['commodity.display'],
                                            'commodity.title' : item['commodity.title'],
                                            'price' : item['commodity.price'],
                                            'measureUnit' : item['commodity.measureUnit'],
                                            'storageLocation.id' : item['storageLocation.id'],
                                            'storageLocation.display' : item['storageLocation.display'],
                                            'batchNo' : item['batchNo'],
                                            'expireDate' : item['expireDate'],
                                            'quantity' : 1,
                                            'discountRate' : 0,
                                            'taxRate' : 0,
                                            'deliveryAmount' : 0,
                                            'discountAmount' : 0
                                    };
                                    $grid.data("gridOptions").calcRowAmount.call($grid, myrowdata);
                                    existRowId = $grid.jqGrid("insertNewRowdata", myrowdata);
                                }
                                
                                var $form = $grid.closest("form");
                                $form.data("formOptions").updateTotalAmount.call($form);
                                
                                var idx = $grid.find("tr[id='" + existRowId + "'] >td.jqgrid-rownum").html().trim();
                                $grid.jqGrid('setRowData', existRowId, {
                                    subVoucher : 100 + idx * 10
                                });
                            }
                        })
                        // 多选模式双击弹出选取框之后，取消当前行编辑状态
                        $grid.closest("div.ui-jqgrid-view").find(".ui-pg-div span.ui-icon-cancel").click();
                    }).keypress(function(event) {
                        return false;
                    });
                }
            },
            align : 'left'
        }, {
            label : '商品名称',
            name : 'commodity.title',
            editable : true,
            editoptions : {
                placeholder : '双击选取',
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.dblclick(function() {
                        $elem.closest(".jqgrow").find("input[name='commodity.sku']").dblclick();
                    }).keypress(function(event) {
                        return false;
                    });
                }
            },
            width : 200,
            editrules : {
                required : true
            },
            align : 'left'
        }, {
            name : 'storageLocation.id',
            hidden : true,
            hidedlg : true,
            editable : true
        }, {
            label : '入库仓库',
            name : 'storageLocation.display',
            width : 150,
            editable : true,
            editrules : {
                required : true
            },
            editoptions : {
                placeholder : '双击选取',
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.dblclick(function() {
                        $elem.closest(".jqgrow").find("input[name='commodity.sku']").dblclick();
                    }).keypress(function(event) {
                        return false;
                    });
                }
            }
        }, {
            label : '批次号',
            name : 'batchNo',
            width : 80,
            editable : true,
            editoptions : {
                placeholder : '双击选取',
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.dblclick(function() {
                        $elem.closest(".jqgrow").find("input[name='commodity.sku']").dblclick();
                    }).keypress(function(event) {
                        return false;
                    });
                }
            }
        }, {
            label : '数量',
            name : 'quantity',
            width : 80,
            formatter : 'number',
            editable : true,
            editrules : {
                required : true,
                number : true
            },
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid);
                    });
                }
            },
            summaryType : 'sum'
        }, {
            label : '销售单价',
            name : 'price',
            width : 80,
            formatter : 'currency',
            editable : true,
            editrules : {
                required : true,
                number : true
            },
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid);
                    });
                }
            },
            summaryType : 'sum'
        }, {
            label : '原始金额',
            name : 'originalAmount',
            width : 80,
            formatter : 'currency',
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $elem = $(elem);
                    $elem.attr("readonly", true);
                }
            },
            responsive : 'sm'
        }, {
            label : '折扣额',
            name : 'discountAmount',
            width : 80,
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid);
                    });
                }
            },
            align : 'right',
            responsive : 'sm'
        }, {
            label : '商品售额',
            name : 'amount',
            width : 80,
            formatter : 'currency',
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid);
                    });
                }
            },
            responsive : 'sm'
        }, {
            label : '售出时成本价',
            name : 'commodityPrice',
            width : 80,
            formatter : 'currency',
            editable : true,
            editoptions : {
                readonly : true
            },
            responsive : 'sm'
        },{
            label : '售出时成本额',
            name : 'commodityAmount',
            width : 80,
            formatter : 'currency',
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid);
                    });
                }
            },
            responsive : 'sm'
        }, {
            label : '是否报废',
            name : 'scrapped',
            width : 80,
            edittype : 'checkbox',
            editable : true,
            align : 'center',
            responsive : 'sm',
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    var $form = $elem.closest("form");
                    $elem.change(function() {

                        if ($elem.is(":checked")) {
                            var rowdata = $grid.jqGrid("getEditingRowdata");
                            rowdata['lossAmount'] = rowdata['commodityAmount'];
                            rowdata['costAmount'] = 0;
                            $grid.jqGrid("setEditingRowdata", rowdata);
                        }

                    });

                }
            },
        }, {
            label : '折损额',
            name : 'lossAmount',
            width : 80,
            formatter : 'currency',
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid);
                    });
                }
            },
            responsive : 'sm'
        }, {
            label : '运费',
            name : 'deliveryAmount',
            width : 80,
            formatter : 'currency',
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    if ($elem.val() == "") {
                        $elem.val(0)
                    }
                    var $form = $elem.closest("form");
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid);
                    });
                }
            },
            responsive : 'sm'
        }, {
            label : '入库总成本',
            name : 'costAmount',
            width : 80,
            formatter : 'currency',
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $elem = $(elem);
                    $elem.attr("readonly", true);
                }
            },
            responsive : 'sm'
        } ],
        footerrow : true,
        beforeInlineSaveRow : function(rowid) {
            var $grid = $(this);
            $grid.data("gridOptions").updateRowAmount.call($grid);
        },
        afterInlineSaveRow : function(rowid) {
            var $grid = $(this);
            // 整个Form相关金额字段更新
            var $form = $grid.closest("form");
            $form.data("formOptions").updateTotalAmount.call($form);
        },
        afterInlineDeleteRow : function(rowid) {
            var $grid = $(this);
            // 整个Form相关金额字段更新
            var $form = $grid.closest("form");
            $form.data("formOptions").updateTotalAmount.call($form);
        },
        userDataOnFooter : true
    });

});
